package com.xujie.sportsmeeting.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.dto.AthleteDTO;
import com.xujie.sportsmeeting.dto.AthleteQueryDTO;
import com.xujie.sportsmeeting.entity.Athlete;
import com.xujie.sportsmeeting.service.AthleteService;
import com.xujie.sportsmeeting.vo.AthleteVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 运动员管理控制器
 */
@Tag(name = "运动员管理", description = "运动员管理相关接口")
@RestController
@RequestMapping("/athlete")
@RequiredArgsConstructor
public class AthleteController {

    private final AthleteService athleteService;

    @Operation(summary = "获取运动员列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('athlete') or authentication.name == 'admin'")
    public Result<IPage<AthleteVO>> getAthleteList(AthleteQueryDTO queryDTO) {
        IPage<Athlete> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        IPage<Athlete> athletePage = athleteService.getAthletePage(page, queryDTO);
        
        // 转换为VO
        IPage<AthleteVO> voPage = athletePage.convert(athlete -> {
            AthleteVO vo = new AthleteVO();
            BeanUtils.copyProperties(athlete, vo);
            // 手动处理BigDecimal到Double的转换
            if (athlete.getHeight() != null) {
                vo.setHeight(athlete.getHeight().doubleValue());
            }
            if (athlete.getWeight() != null) {
                vo.setWeight(athlete.getWeight().doubleValue());
            }
            return vo;
        });
        
        return Result.success(voPage);
    }

    @Operation(summary = "获取运动员详情")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('athlete') or authentication.name == 'admin'")
    public Result<AthleteVO> getAthleteDetail(@PathVariable Long id) {
        Athlete athlete = athleteService.getById(id);
        if (athlete == null) {
            return Result.error("运动员不存在");
        }
        
        AthleteVO vo = new AthleteVO();
        BeanUtils.copyProperties(athlete, vo);
        // 手动处理BigDecimal到Double的转换
        if (athlete.getHeight() != null) {
            vo.setHeight(athlete.getHeight().doubleValue());
        }
        if (athlete.getWeight() != null) {
            vo.setWeight(athlete.getWeight().doubleValue());
        }
        
        return Result.success(vo);
    }

    @Operation(summary = "创建运动员")
    @PostMapping
    @PreAuthorize("hasAuthority('athlete:add') or authentication.name == 'admin'")
    public Result<Void> createAthlete(@Valid @RequestBody AthleteDTO athleteDTO) {
        Athlete athlete = new Athlete();
        BeanUtils.copyProperties(athleteDTO, athlete);
        
        boolean success = athleteService.createAthlete(athlete);
        if (success) {
            return Result.success("运动员创建成功");
        } else {
            return Result.error("运动员创建失败");
        }
    }

    @Operation(summary = "更新运动员信息")
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('athlete:edit') or authentication.name == 'admin'")
    public Result<Void> updateAthlete(@PathVariable Long id, @Valid @RequestBody AthleteDTO athleteDTO) {
        Athlete athlete = new Athlete();
        BeanUtils.copyProperties(athleteDTO, athlete);
        athlete.setId(id);
        
        boolean success = athleteService.updateAthlete(athlete);
        if (success) {
            return Result.success("运动员更新成功");
        } else {
            return Result.error("运动员更新失败");
        }
    }

    @Operation(summary = "删除运动员")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('athlete:delete') or authentication.name == 'admin'")
    public Result<Void> deleteAthlete(@PathVariable Long id) {
        boolean success = athleteService.removeById(id);
        if (success) {
            return Result.success("运动员删除成功");
        } else {
            return Result.error("运动员删除失败");
        }
    }

    @Operation(summary = "批量删除运动员")
    @DeleteMapping("/batch")
    @PreAuthorize("hasAuthority('athlete:delete') or authentication.name == 'admin'")
    public Result<Void> batchDeleteAthletes(@RequestBody List<Long> ids) {
        boolean success = athleteService.removeByIds(ids);
        if (success) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    @Operation(summary = "启用/禁用运动员")
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('athlete:edit') or authentication.name == 'admin'")
    public Result<Void> toggleAthleteStatus(@PathVariable Long id, @RequestBody StatusRequest request) {
        boolean success = athleteService.updateAthleteStatus(id, request.getStatus());
        if (success) {
            return Result.success("运动员状态更新成功");
        } else {
            return Result.error("运动员状态更新失败");
        }
    }

    // 内部请求类
    public static class StatusRequest {
        private Integer status;
        
        public Integer getStatus() {
            return status;
        }
        
        public void setStatus(Integer status) {
            this.status = status;
        }
    }
}
